//
//  ViewControllerManager.m
//  18Birdies
//
//  Created by Lc on 15/4/17.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "BaseViewController.h"
#import "UIViewController+Lc.h"
#import "LcFoundation.h"
#import "ViewControllerManager.h"

@implementation ViewControllerManager

- (UIViewController*)currentViewController {
  return [UIViewController currentViewController];
}

- (int)viewControllerCount {
  UIViewController* rootViewController = nil;
  for (UIWindow* window in [UIApplication sharedApplication].windows) {
    if (window.rootViewController != nil) {
      rootViewController = window.rootViewController;
      break;
    }
  }
  LC_CHECK_NOT_NULL(rootViewController);
  return [self subviewControllerCount:rootViewController];
}

- (int)subviewControllerCount:(UIViewController*)viewController {
  if (![viewController isKindOfClass:BaseViewController.class] &&
      ![viewController isKindOfClass:UINavigationController.class]) {
    return 0;
  }
  if ([viewController isKindOfClass:UINavigationController.class]) {
    UINavigationController* navigationController = (UINavigationController*)viewController;
    return (int)navigationController.viewControllers.count +
           [self subviewControllerCount:navigationController.presentedViewController];
  } else {
    return 1 + [self subviewControllerCount:viewController.presentedViewController];
  }
}

- (BOOL)isView:(UIViewController*)viewController sourceFrom:(Class)aClass {
  UINavigationController* navigationController = nil;
  if (viewController.presentingViewController != nil) {
    navigationController = (UINavigationController*)viewController.presentingViewController;
  } else {
    navigationController = viewController.navigationController;
  }
  for (UIViewController* subViewController in navigationController.viewControllers) {
    if ([subViewController isKindOfClass:aClass.class]) {
      return YES;
    }
  }
  return NO;
}

@end
